package com.kuangstudy.caffeine.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheWriter;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.util.concurrent.TimeUnit;

/**
 * @author ryt
 * @date 2023-10-9
 */
@Configuration
@Slf4j
public class CaffeineConfig {

    @Bean
    @Primary
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                //缓存写入/删除 监控
                .writer(new CacheWriter<Object, Object>() {
                    @Override
                    public void write(Object key, Object value) { //此方法是同步阻塞的
                        log.info("--缓存写入--: key={}, value={}", key, value);
                    }

                    @Override
                    public void delete(Object key, Object value, RemovalCause cause) {
                        log.info("--缓存删除--:key= {}", key);
                    }
                })
                .build();
    }

}
